﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Libra.Receipt.Application.Entity;
using Microsoft.AspNetCore.Http;
namespace Libra.Receipt.Application;

/// <summary>
/// 过磅记录表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class WeightLogService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<WeightLog> _weightLogRep;

    public WeightLogService(SqlSugarRepository<WeightLog> weightLogRep)
    {
        _weightLogRep = weightLogRep;
    }

    /// <summary>
    /// 分页查询过磅记录表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询过磅记录表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<WeightLogOutput>> Page(PageWeightLogInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _weightLogRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.Keyword), u => u.ProjectName.Contains(input.Keyword) || u.LicensePlate.Contains(input.Keyword) || u.OriginalLicensePlate.Contains(input.Keyword) || u.WeightCurveOssUrl.Contains(input.Keyword) || u.WeightImageUrl.Contains(input.Keyword) || u.WeightVideoUrl.Contains(input.Keyword) || u.MaterialDetailId.Contains(input.Keyword))
            .WhereIF(input.ProjectId != null, u => u.ProjectId == input.ProjectId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProjectName), u => u.ProjectName.Contains(input.ProjectName.Trim()))
            .WhereIF(input.DeviceId != null, u => u.DeviceId == input.DeviceId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.LicensePlate), u => u.LicensePlate.Contains(input.LicensePlate.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OriginalLicensePlate), u => u.OriginalLicensePlate.Contains(input.OriginalLicensePlate.Trim()))
            .WhereIF(input.WeighingTimeRange?.Length == 2, u => u.WeighingTime >= input.WeighingTimeRange[0] && u.WeighingTime <= input.WeighingTimeRange[1])
            .WhereIF(input.WeighingStartTimeRange?.Length == 2, u => u.WeighingStartTime >= input.WeighingStartTimeRange[0] && u.WeighingStartTime <= input.WeighingStartTimeRange[1])
            .WhereIF(input.WeighingEndTimeRange?.Length == 2, u => u.WeighingEndTime >= input.WeighingEndTimeRange[0] && u.WeighingEndTime <= input.WeighingEndTimeRange[1])
            .WhereIF(!string.IsNullOrWhiteSpace(input.WeightCurveOssUrl), u => u.WeightCurveOssUrl.Contains(input.WeightCurveOssUrl.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WeightImageUrl), u => u.WeightImageUrl.Contains(input.WeightImageUrl.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WeightVideoUrl), u => u.WeightVideoUrl.Contains(input.WeightVideoUrl.Trim()))
            .WhereIF(input.SyncTimeRange?.Length == 2, u => u.SyncTime >= input.SyncTimeRange[0] && u.SyncTime <= input.SyncTimeRange[1])
            .WhereIF(!string.IsNullOrWhiteSpace(input.MaterialDetailId), u => u.MaterialDetailId.Contains(input.MaterialDetailId.Trim()))
            .Select<WeightLogOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加过磅记录表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加过磅记录表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddWeightLogInput input)
    {
        var entity = input.Adapt<WeightLog>();
        return await _weightLogRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 删除过磅记录表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除过磅记录表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteWeightLogInput input)
    {
        var entity = await _weightLogRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _weightLogRep.FakeDeleteAsync(entity);   //假删除
        //await _weightLogRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除过磅记录表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除过磅记录表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete(BatchDeleteWeightLogInput input)
    {
        var list = await _weightLogRep.AsQueryable().Where(u => input.IdList.Contains(u.Id)).ToListAsync() ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        return await _weightLogRep.FakeDeleteAsync(list);   //假删除
        //return await _weightLogRep.DeleteAsync(list);   //真删除
    }

    /// <summary>
    /// 更新过磅记录表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新过磅记录表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateWeightLogInput input)
    {
        var entity = input.Adapt<WeightLog>();
        await _weightLogRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取过磅记录表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取过磅记录表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<WeightLog> Detail([FromQuery] QueryByIdWeightLogInput input)
    {
        return await _weightLogRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取过磅记录表列表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取过磅记录表列表")]
    [ApiDescriptionSettings(Name = "List"), HttpGet]
    public async Task<List<WeightLogOutput>> List([FromQuery] PageWeightLogInput input)
    {
        return await _weightLogRep.AsQueryable().Select<WeightLogOutput>().ToListAsync();
    }

    /// <summary>
    /// 下载过磅记录表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载过磅记录表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportWeightLogOutput>(), "过磅记录表导入模板");
    }

    /// <summary>
    /// 导入过磅记录表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入过磅记录表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportWeightLogInput, WeightLog>(file, (list, markerErrorAction) =>
            {
                _weightLogRep.Context.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<WeightLog>>();
                    
                    var storageable = _weightLogRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.ProjectName?.Length > 128, "项目名称长度不能超过128个字符")
                        .SplitError(it => it.Item.LicensePlate?.Length > 32, "车牌号长度不能超过32个字符")
                        .SplitError(it => it.Item.OriginalLicensePlate?.Length > 32, "原始车牌号长度不能超过32个字符")
                        .SplitError(it => it.Item.WeightCurveOssUrl?.Length > 1024, "称重曲线保存路径-相对路径长度不能超过1024个字符")
                        .SplitError(it => it.Item.WeightImageUrl?.Length > 1024, "称重照片保存路径-相对路径长度不能超过1024个字符")
                        .SplitError(it => it.Item.WeightVideoUrl?.Length > 1024, "称重视频保存路径-相对路径长度不能超过1024个字符")
                        .SplitError(it => it.Item.MaterialDetailId?.Length > 1024, "收料单id长度不能超过1024个字符")
                        .SplitError(it => it.Any(), "记录已存在")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });

            return stream;
        }
    }
}
